﻿//<![CDATA[
    // Runs on load to hookup events to control changes
    function SetupDirtyStateManagement()
    {
        document.body.onclick=SetControlChange;    
        document.body.onkeyup=SetControlChange;        
    }

    var isDirty = false;
    // Variable to hold UserDefinedValidation function, sometimes used with ActivityIndicator.
    // We add a dirty check to validation if it exists, so the activity indicator doesn't appear
    // if the page is dirty.  That way, if they cancel the confirm box, the activity indicator
    // isn't still displayed.
    var userDefinedValidation;
    if (typeof(UserDefinedValidation) == 'function')
    {
        userDefinedValidation = UserDefinedValidation;
        UserDefinedValidation = CheckDirtyAndValidate;
    }

    function CheckDirtyAndValidate()
    {
        // we know userDefinedValidation is a function, or we wouldn't be in here
        var valid = userDefinedValidation();
        return (valid && !isDirty);
    }

    function SetDirty()    
    {        
        isDirty = true;
    }        
    
    function ClearDirty()    
    {        
        isDirty = false;
    }            
   
    function IsDirty()
    {
        return isDirty;
    }   
   
    function CheckDirty()    
    {
        if ( IsDirty() )
        {
            // Clear this so we don't get the double messages when clicking a LinkButton 
            // in the header;
            window.onbeforeunload = null;
            return "Unsaved changes have been made to this page. Please save your changes before continuing. Any changes not saved will be lost.";
        }
    }        
    
    function SetControlChange(evt)    
    {
        evt = evt || window.event;
        target = evt.target || window.event.srcElement;
        var targetID = target.getAttribute("id"); 
        if( targetID != "" && typeof(target) != 'undefined' )
        {  
            var aIds = controlIdsToSkipDirtyChecks.split(",");
            for (i=0; i < aIds.length; i++)
            {
                if ( aIds[i] == targetID )
                {
                    // the focused control is exempted from dirty state checking
                    // if another control is clicked, the event will be re-wired
                    window.onbeforeunload = null;
                    return;
                }
            }
            window.onbeforeunload=CheckDirty;
            var old = (target.onchange) ? target.onchange : function () {};
            if (old.toString().indexOf('doPostBack') == -1)
                target.onchange = function () {old(); SetDirty()};
        }    
    }

//]]>
